package com.xinke.edu.mypetadoption.fragment2;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.xinke.edu.mypetadoption.databinding.FragmentSpBinding;
import com.xinke.edu.mypetadoption.entity.MerchantInfoDTO;
import com.xinke.edu.mypetadoption.entity.Product;
import com.xinke.edu.mypetadoption.entity.ResultBody;
import com.xinke.edu.mypetadoption.fragment2.activity.Sj_FbProductActivity;
import com.xinke.edu.mypetadoption.fragment2.adapter.SpAdpter;
import com.xinke.edu.mypetadoption.util.RetrofitUtil;
import com.xinke.edu.mypetadoption.util.SPUtils;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class SpFragment extends Fragment {

    private FragmentSpBinding binding;
    private SpAdpter spAdpter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = FragmentSpBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 1️⃣ 初始化适配器
        spAdpter = new SpAdpter();

        // 2️⃣ RecyclerView 竖向列表布局
        binding.recyclerview.setLayoutManager(
                new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        );
        binding.recyclerview.setAdapter(spAdpter);

        binding.sjTjsp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), Sj_FbProductActivity.class);
                startActivity(intent);
            }
        });

        // 3️⃣ 监听点击事件（可选）
        spAdpter.setOnItemClickListener((adapter, itemView, position) -> {
            Product p = (Product) adapter.getItem(position);
            if (p != null) {
                Toast.makeText(requireContext(),
                        "点击：" + p.getName() + " ￥" + p.getPrice(),
                        Toast.LENGTH_SHORT).show();
                // TODO: 可跳转到商品详情
            }
        });

        // 4️⃣ 调用接口加载数据
        loadProducts();
    }

    private void loadProducts() {
        // 获取登录用户ID
        int userId = SPUtils.getInstance(requireContext()).getInt("userId", 1);
        Log.d("SpFragment", "当前登录用户ID: " + userId);
        
        // 先查询商家信息
        RetrofitUtil.getApi().getMerchantInfo(userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResultBody<MerchantInfoDTO>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {}

                    @Override
                    public void onNext(@NonNull ResultBody<MerchantInfoDTO> result) {
                        Log.d("SpFragment", "获取商家信息成功");
                        // 由于MerchantInfoDTO没有商家ID字段，暂时使用用户ID作为商家ID
                        // 实际应该从merchant表中查询对应的商家ID
                        queryProductsByMerchantId(userId);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("SpFragment", "获取商家信息失败", e);
                        Toast.makeText(requireContext(), "获取商家信息失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        // 失败时仍然尝试使用用户ID查询商品
                        queryProductsByMerchantId(userId);
                    }

                    @Override
                    public void onComplete() {}
                });
    }
    
    private void queryProductsByMerchantId(int merchantId) {
        Log.d("SpFragment", "使用商家ID: " + merchantId + " 查询商品列表");
        
        RetrofitUtil.getApi().spProduct(String.valueOf(merchantId))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResultBody<List<Product>>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {}

                    @Override
                    public void onNext(@NonNull ResultBody<List<Product>> result) {
                        List<Product> list = result.getData();
                        if (list != null && !list.isEmpty()) {
                            // 使用addAll方法添加数据，适配BaseQuickAdapter
                            spAdpter.addAll(list);
                            Log.d("SpFragment", "成功加载商品数量: " + list.size());
                        } else {
                            Log.d("SpFragment", "未找到商品数据");
                            Toast.makeText(requireContext(), "暂无商品数据", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("SpFragment", "查询商品失败", e);
                        Toast.makeText(requireContext(), "加载商品失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        Log.d("SpFragment", "商品加载完成");
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
